/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.keepalive;

import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.logos.common.daemon.AbsWorkService;
import com.logos.common.keepalive.util.NotificationUtil;
import com.logos.tool.location.ILocation;
import com.logos.tool.location.IMapLocationChangedListener;
import com.logos.tool.location.MapLocationOperation;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by llx on 2018/11/7.
 */
public class UpPointService extends AbsWorkService {

    //是否 任务完成, 不再需要服务运行?
    public static boolean sShouldStopService;
    private static MapLocationOperation sOperation;
    private IMapLocationChangedListener mListener = new IMapLocationChangedListener() {
        @Override
        public void onMapLocationChangedListener(final ILocation location) {
        }
    };
    private int count = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        return sShouldStopService;
    }

    @Override
    public void startWork(Intent intent, int flags, int startId) {
        count++;
        if (count > 1) {

            if (sOperation != null) {
                sOperation.start();
            } else {
                sOperation = new MapLocationOperation(this);
                sOperation.setAccuracyLevel(MapLocationOperation.AccuracyLevel.HEIGHT);
                sOperation.setInterval(3000);
                sOperation.setMapLocationChangedListener(mListener);
                sOperation.start();
            }
            NotificationUtil.notify(NotificationUtil.NOTIFICATION_ID_BASE, this);
        }
    }

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
        stopService();
    }

    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {
        return null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent, Void alwaysNull) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
        if (sOperation != null) {
            sOperation.stop();
        }
    }

    /**
     * 停止服务且停止进程守护
     */
    public static void stopService() {
        cancelJobAlarmSub();
        if (sOperation != null) {
            sOperation.stop();
            sOperation.destroy();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
